package com.example.gobang_system.api;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 *  实现一个 WebSocketHandler
 */
@Component
public class WebSocketHandler extends TextWebSocketHandler {
    /**
     *  建立连接之后触发的方法.
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功");
    }

    /**
     *  客户端给服务器发送文本数据时, 该方法可以感知到消息内容
     */
    @Override
    protected void handleTextMessage(WebSocketSession webSocketSession, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());
        // 将数据返回
        webSocketSession.sendMessage(message);
    }

    /**
     *  传输出现异常, 如: 网络波动导致断开连接, 就会触发该函数
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常");
    }

    /**
     * 连接被关闭(断开连接, 下线), 就会触发该函数
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭");
    }
}
